/*
 * @Author: Turump 
 * @Date: 2021-04-25 19:58:58 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-05-13 17:44:28
 * 动作类任务基类
 */

import { TweenType } from "../../misc/TweenType";
import { TaskBase } from "../TaskBase";
import { TaskEnableType } from "../TaskEnableType";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ActionBaseTask extends TaskBase {

    @property({ displayName: "重复任务", override: true, visible: false })
    repeatableTask = false;

    @property({ displayName: "动作执行时长" })
    actionDuration = 0.5;

    @property({ displayName: "完成发送事件" })
    isEmitDoneEvent = false;

    @property({ displayName: "事件名称", override: true, visible() { return this.isEmitDoneEvent == true } })
    doneEvent = ""

    @property({ displayName: "动作带音效" })
    withAudio = false
    @property({ displayName: "动作伴随的音效", type: cc.AudioClip, visible() { return this.withAudio == true } })
    actionAudio: cc.AudioClip = null;

    @property({ displayName: "缓动类型", type: cc.Enum(TweenType) })
    easeType: TweenType = TweenType.linear;

    protected actionTween: cc.Tween = null;
    //用于保存action原来的step函数
    private oldStep = null;

    enableTask() {
        if(this.enableType == TaskEnableType.OnStart){
            this.delayTime = 0;
        }
        super.enableTask();
        let tween = this.getAction().call(()=>{
            this.emitDoneEvent();
        });
        this.actionTween = tween.target(this.node).start();
    }

    pauseTask() {
        super.pauseTask();
        if(this.actionTween) {
            let tweenFinalAction = this.actionTween['_finalAction']
            if(tweenFinalAction) {
                this.oldStep = tweenFinalAction.step
                tweenFinalAction.step = ()=>{}
            }
        }
    }

    resmueTask() {
        super.resmueTask();
        if (this.actionTween && this.oldStep) {
            let tweenFinalAction = this.actionTween['_finalAction']
            tweenFinalAction.step = this.oldStep;
        }
    }

    stopTask() {
        this.actionTween && this.actionTween.stop();
        this.enabled = false;
    }

    protected getAction(): cc.Tween | null {
        cc.error(`${this.name} child class must implemetion getAction`);
        return
    }

    protected getPlayAudioTween() {
        return cc.tween(this.node).call(() => {
            if (this.withAudio && this.actionAudio)
                cc.audioEngine.playEffect(this.actionAudio, false);
        })
    }

    protected getReverseEasingString() {
        let easeStr = Object.keys(TweenType)[this.easeType];
        cc.log('ActionBaseTask getReverseEasing of', easeStr)
        if (easeStr.indexOf('In') > -1 && easeStr.indexOf('Out') > -1) {
            return easeStr;
        }
        if (easeStr.indexOf('In') > -1)
            return easeStr.replace('In', 'Out');

        if (easeStr.indexOf('In') > -1)
            return easeStr.replace('Out', 'In');
        return easeStr;
    }
}
